package com.dodo.blog.ui.component.input;

import com.dodo.blog.RequestCycle;
import com.dodo.blog.ui.component.HtmlComponent;
import com.dodo.blog.ui.component.container.Container;
import com.dodo.blog.ui.page.Page;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class Anchor
        extends Container
{
    private static final long serialVersionUID = 1L;

    private Map<String, String> params = new HashMap<String, String>();

    public Anchor( String id, HtmlComponent component, String href )
    {
        super( Tag.ANCHOR );
        setId( id );
        add( component );
        setHref( href );
    }

    public Anchor( String id, String text, String href )
    {
        super( Tag.ANCHOR );
        setId( id );
        setInnerHtml( text );
        setHref( href );
    }

    public Anchor( String id, String text, Class<? extends Page> pageClass )
    {
        this( id, text, RequestCycle.get().getWebApplication().getPathByPageClass( pageClass ) );
    }

    public Anchor( String text, Class<? extends Page> pageClass )
    {
        this( "", text, RequestCycle.get().getWebApplication().getPathByPageClass( pageClass ) );
    }

    public Anchor addParameter( String name, String value )
    {
        params.put( name, value );
        return this;
    }

    public Anchor addParameter( String name, Long value )
    {
        params.put( name, value != null ? value.toString() : null );
        return this;
    }

    public Anchor()
    {
        this( "", "", "" );
    }

    public Anchor( String id )
    {
        this( id, "", "" );
    }

    public Anchor( String id, String text )
    {
        this( id, text, "" );
    }

    public Anchor setHref( String href )
    {
        if ( href != null && href.trim().length() > 0 )
        {
            setAttribute( Attribute.HREF, href );
        }

        return this;
    }

    public Anchor setReadOnly()
    {
        setAttribute( Attribute.READONLY );
        return this;
    }

    public Anchor setDisabled()
    {
        setAttribute( Attribute.DISABLED );
        return this;
    }

    @Override
    public StringBuilder render()
    {
        String href = getAttribute( Attribute.HREF );
        if ( !StringUtils.isBlank( href ) )
        {
            String mark = "?";
            int i = 0;
            for ( Map.Entry<String, String> p : params.entrySet() )
            {
                if ( i > 0 )
                {
                    mark = "&";
                }

                setAttribute( Attribute.HREF, href + mark + p.getKey() + "=" + p.getValue() );
            }
        }

        return super.render();
    }
}
